# src/crud/sys_menu.py
from typing import List, Optional, Dict, Any
from sqlalchemy.orm import Session
from src.models import sys_menu as models
from src.schemas import sys_menu as schemas
from src.schemas import request_model
from src.core import orm_curd
from src.schemas.login_manager import AuthManager
from src.core import retMes


# ---------------------- 单条新增 ----------------------
def create_menu(db: Session,
                auth: AuthManager,
                menu: schemas.SysMenuCreate) -> dict:
    """
    新增单条菜单。
    """
    return orm_curd.Insert(
        db,
        auth,
        models.SysMenu,
        schemas.SysMenu,
        "系统菜单",
        [menu.dict()],
        ["api_id", "menu_index"],  # 业务唯一键
        skip_duplicates=True
    )


# ---------------------- 批量新增 ----------------------
def create_menus(db: Session,
                 auth: AuthManager,
                 menus: List[schemas.SysMenuCreate]) -> dict:
    """
    批量新增菜单。
    """
    return orm_curd.Insert(
        db,
        auth,
        models.SysMenu,
        schemas.SysMenu,
        "系统菜单",
        menus,
        ["api_id", "menu_index"],
        skip_duplicates=True
    )


# ---------------------- 分页查询 ----------------------
def get_menus(db: Session,
              auth: AuthManager,
              page: int = 0,
              page_size: int = 100,
              FilterModel: Optional[request_model.QueryModel] = None,
              id: Optional[str] = None) -> dict:
    """
    分页查询菜单列表。
    """
    return orm_curd.query_with_page(
        db,
        auth,
        models.SysMenu,
        schemas.SysMenu,
        id=id,
        filter_model=FilterModel,
        page=page,
        page_size=page_size
    )


# ---------------------- 单条更新 ----------------------
def update_menu(db: Session,
                auth: AuthManager,
                menu_id: str,
                menu: schemas.SysMenu) -> schemas.SysMenu:
    """
    更新单条菜单。
    """
    update_model = request_model.UpdateModel([
        request_model.UpdateItem(
            pk_names=["id"],
            pk_values=[menu_id],
            data=menu.dict(exclude_unset=True)
        )
    ])
    return orm_curd.update(
        db,
        auth,
        models.SysMenu,
        update_model
    )


# ---------------------- 批量更新 ----------------------
def update_menus(db: Session,
                 auth: AuthManager,
                 updateModel: request_model.UpdateModel) -> dict:
    """
    批量更新菜单。
    """
    return orm_curd.update(
        db,
        auth,
        models.SysMenu,
        updateModel
    )


# ---------------------- 删除 ----------------------
def delete_menus(db: Session,
                 auth: AuthManager,
                 deleteModel: request_model.DeleteModel) -> dict:
    """
    删除菜单（硬删除）。
    """
    return orm_curd.delete(
        db=db,
        auth=auth,
        model_cls=models.SysMenu,
        delete_obj=deleteModel
    )


